package alvarodelrosal.chat.client.modelo;

import alvarodelrosal.chat.client.chataction.local.ChatBye;
import alvarodelrosal.chat.client.chataction.local.ChatLocalAction;
import alvarodelrosal.chat.client.chataction.local.ChatLocalActionFactory;
import alvarodelrosal.chat.client.gui.Dialogo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Connection extends Thread {

    private Socket socketCliente = null;
    private static PrintWriter output = null;
    private static BufferedReader input = null;

    public Connection(String host, int puerto) {
        try {
            socketCliente = new Socket(host, puerto);
            output = new PrintWriter(socketCliente.getOutputStream(), true);
            input = new BufferedReader(new InputStreamReader(socketCliente.getInputStream()));
        } catch (UnknownHostException ex) {
            Dialogo.pintarMensajeDeError("Error de conexión",
                    "El host indicado no se puede alcanzar. Compruebe su conexion.");
        } catch (IOException ex) {
            Dialogo.pintarMensajeDeError("Error de conexión",
                    "El host indicado no se puede alcanzar. Compruebe que el servidor está iniciado.");
            try {
                if (socketCliente != null) {
                    socketCliente.close();
                }
            } catch (IOException ex1) {
            } finally {
                if (output != null) {
                    output.close();
                }
            }
        }
    }
    
    @Override
    public void run() {
        String inputRequest = "";
        try {
            inputRequest = input.readLine();
        } catch (IOException ex) {
            Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        ChatBye bye = new ChatBye();
        while(!bye.getName().equals(inputRequest)) {
            if (serverIsOff(inputRequest)) {
                return;
            } else {
                String command = getsTheCommand(inputRequest);
                List<String> parameters = getsTheParameters(inputRequest);
                executesThe(command, parameters);
                try {
                    inputRequest = input.readLine();
                } catch (IOException ex) {
                    Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
    }

    private void executesThe(String command, List<String> parameters) {
        ChatLocalActionFactory factory = new ChatLocalActionFactory();
        ChatLocalAction action = factory.getTheAction(command);
        action.doAction(parameters);
    }

    private boolean serverIsOff(String inputRequest) {
        return inputRequest == null;
    }

    private String getsTheCommand(String inputRequest) {
        String[] strippedString = inputRequest.split("<:@:>");
        return strippedString[0];
    }

    private List<String> getsTheParameters(String inputRequest) {
        List<String> parameters = new ArrayList();
        String[] strippedString = inputRequest.split("<:@:>");
        
        for (int position = 1; position < strippedString.length; position++) {
            parameters.add(strippedString[position]);
        }
        
        return parameters;
    }
    
    public static void sendToServer(String out) {
        output.println(out);
    }

}
